#Include Once "Windows.bi"
#LibPath "Lib"



#Include "Inc\xrtl.bi"
#Include "Inc\EasyCKL.bi"



Dim hInstance As HINSTANCE = GetModuleHandle(NULL)
Dim Shared hWnd As HWND
Dim Shared browser As Any Ptr



Function DlgProc(ByVal hWin As HWND, ByVal uMsg As UINT, ByVal wParam As WPARAM, ByVal lParam As LPARAM) As Integer
	Select Case uMsg
		Case WM_DESTROY
			PostQuitMessage(0)
		Case WM_SIZE
			MoveWindow(Chrome_GetWindowHandle(browser), 0, 0, LOWORD(lParam), HIWORD(lParam), FALSE)
		Case Else
			return DefWindowProc(hWin, uMsg, wParam, lParam)
	End Select
	Return 0
End Function

Sub CallBack_ChTitle(dwId As LONG_PTR, szTitle As WString Ptr)
	SetWindowText(hWnd, xRtl.Charset.W2A(szTitle))
End Sub

Sub V8_Init(context As Any Ptr)
	Print 1
	Chrome_AddJSFunction(context, xRtl.Charset.A2W("xTest"))
End Sub

Function V8_CallBack(sname As WString Ptr, argu As Any Ptr, retval As Any Ptr) As BOOL
	Print *sname
	Dim i As Integer = Chrome_GetV8ValueListSize(argu)
	For j As Integer = 0 To i - 1
		Print Chrome_GetV8ValueInt(argu, j)
	Next
	Return TRUE
End Function



Chrome_SetV8ContextCallback(@V8_Init, @V8_CallBack)
Chrome_InitializeEx(hInstance, INITFLAG_CACHESTORAGE Or INITFLAG_ENABLEHIGHDPISUPPORT, NULL, xRtl.Charset.A2W("zh-CN"), 0)
Chrome_EnableCookieStorage()
If Chrome_IsUIThread() = 0 Then ExitProcess(0)

Dim wcex As WNDCLASSEX

wcex.cbSize = SizeOf(WNDCLASSEX)
wcex.style = CS_HREDRAW Or CS_VREDRAW
wcex.lpfnWndProc = @DlgProc
wcex.cbClsExtra = 0
wcex.cbWndExtra = 0
wcex.hInstance = hInstance
wcex.hIcon = 0
wcex.hCursor = LoadCursor(NULL, IDC_ARROW)
wcex.hbrBackground = COLOR_WINDOW + 1
wcex.lpszMenuName = 0
wcex.lpszClassName = StrPtr("xWeb_Window")
wcex.hIconSm = 0
RegisterClassEx(@wcex)

hWnd = CreateWindow("xWeb_Window", "xWeb", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, 800, 600, NULL, NULL, hInstance, NULL)

If hWnd = 0 Then ExitProcess(0)
Dim BrowserCallbacks As BROWSER_CALLBACKS
BrowserCallbacks.cbSize = SizeOf(BROWSER_CALLBACKS)
BrowserCallbacks.chtitle_callback = @CallBack_ChTitle

Dim As RECT rcWindowClient, rcWebControl
GetClientRect(hWnd, @rcWindowClient)
rcWebControl.top = rcWebControl.left = 0
rcWebControl.bottom = rcWindowClient.bottom
rcWebControl.right = rcWindowClient.right

browser = Chrome_CreateChildBrowser(BROWSERFLAG_SYNC, @BrowserCallbacks, 0, 0, xRtl.Charset.A2W("http://www.baidu.com"), hWnd, @rcWebControl, 0)
'Chrome_ShowDevTools(browser)

ShowWindow(hWnd, SW_SHOW)
UpdateWindow(hWnd)

Chrome_MessageLoop()
Chrome_Shutdown()
ExitProcess(0)